//
//  PhotoBrowserViewController.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/18.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

//可重用id
let  PhotoBrowserViewCellId = "PhotoBrowserViewCellId"
class PhotoBrowserViewController: UIViewController {
    //图像数组
    var urls: [NSURL]
    // 选中照片索引
    var selectedIndexPath: NSIndexPath
    
    //MARK: - 监听方法
    @objc private func save() {
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        
        guard let image = cell.imageView.image else {
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func image(image:UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        
        let message = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserLayout())
    private lazy var saveButton = UIButton(title: "保存", fontSize: 14, ImageName: nil, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    private lazy var closeButton = UIButton(title: "关闭", fontSize: 14, ImageName: nil, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    
    //MARK: - 构造函数
    init(urls: [NSURL], indexPath: NSIndexPath){
        self.urls = urls
        self.selectedIndexPath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 生命周期方法
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        
        view = UIView(frame: rect)
        
        setupUI()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)

        // Do any additional setup after loading the view.
    }
    //MARK: - 自定义流水布局
    private class PhotoBrowserLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            super.prepareLayout()
            
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            scrollDirection = .Horizontal
            
            collectionView?.bounces = false
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            
        }
    }
}
//MARK: - 设置界面
private extension PhotoBrowserViewController {
    func setupUI() {
        
        view.backgroundColor = UIColor.blackColor()
        
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        collectionView.frame = view.bounds
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-28)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        //添加监听方法
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        //准备collectionView
        prepareCollectionView()
    }
    
    func prepareCollectionView() {
        //注册可重用cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserViewCellId)
        //设置数据源
        collectionView.dataSource = self
    }
}
//MARK: - collectionView数据源方法
extension PhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserViewCellId, forIndexPath: indexPath) as! PhotoBrowserCell
        cell.photoDelegate = self
        cell.imageURL = urls[indexPath.item]
        
        return cell
    }

}
//MARK: - PhotoBrowserCellDelegate
extension PhotoBrowserViewController: PhotoBrowserCellDelegate {
    func PhotoBrowserCellDidClickImage() {
        close()
    }
}
//MARK: - PhotoBrowserDismissDelegate
extension PhotoBrowserViewController: PhotoBrowserDismissDelegate {
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        iv.image = cell.imageView.image
        iv.frame = cell.scrollView.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return iv
    }
    func indexPathForDismiss() -> NSIndexPath {
        
        return collectionView.indexPathsForVisibleItems()[0]
    }
}

